import { ref } from 'vue'
import type { Episode } from '../api/drama'

export interface SubtitleFormData {
  videoId: string
  videoUrl: string
  languages: string[]
  sourceLanguage: string
  srtOutputPath?: string
  includeSourceLanguage?: boolean
}

export function useFormValidation() {
  const formErrors = ref<Record<string, string>>({})

  const validateSubtitleForm = (form: Partial<SubtitleFormData>, selectedEpisodes: Episode[]) => {
    const errors: Record<string, string> = {}
    
    if (!form.languages || form.languages.length === 0) {
      errors.languages = '请至少选择一种语言'
    }
    
    if (selectedEpisodes.length === 0) {
      errors.episodes = '请选择要处理的剧集'
    }
    
    if (!form.sourceLanguage) {
      errors.sourceLanguage = '请选择源语言'
    }
    
    formErrors.value = errors
    return {
      valid: Object.keys(errors).length === 0,
      errors
    }
  }

  const validateDramaForm = (form: Partial<SubtitleFormData>, episodes: Episode[]) => {
    const errors: Record<string, string> = {}
    
    if (!form.languages || form.languages.length === 0) {
      errors.languages = '请至少选择一种语言'
    }
    
    const enabledEpisodes = episodes.filter(ep => ep.status === 0)
    if (enabledEpisodes.length === 0) {
      errors.episodes = '该剧没有已启用的剧集可供请求'
    }
    
    if (!form.sourceLanguage) {
      errors.sourceLanguage = '请选择源语言'
    }
    
    formErrors.value = errors
    return {
      valid: Object.keys(errors).length === 0,
      errors
    }
  }

  const clearErrors = () => {
    formErrors.value = {}
  }

  return {
    formErrors,
    validateSubtitleForm,
    validateDramaForm,
    clearErrors
  }
}